package com.lxs.gitee001.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lxs.gitee001.constant.AccountConstant;
import com.lxs.gitee001.constant.ClientConstant;
import com.lxs.gitee001.model.response;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class GiteeOAuthService {

    private String clientId;
    private String clientSecret;
    private String redirectUri;
    private String userName;
    private String passWord;

    public GiteeOAuthService() {
        this.clientId = ClientConstant.CLIENT_ID;
        this.clientSecret = ClientConstant.CLIENT_SECRET;
        this.redirectUri = ClientConstant.REDIRECT_URI;
        this.userName = AccountConstant.USERNAME;
        this.passWord = AccountConstant.PASSWORD;
    }

    /**
     * 使用密码模式获取access_token
     */
    public response.TokenResponse getAccessTokenByPassword(String scope) throws IOException {
        String url = "https://gitee.com/oauth/token";

        // 构建请求参数
        String params =
                "grant_type=password" +
                        "&username=" + URLEncoder.encode(userName, "UTF-8") +
                        "&password=" + URLEncoder.encode(passWord, "UTF-8") +
                        "&client_id=" + URLEncoder.encode(clientId, "UTF-8") +
                        "&client_secret=" + URLEncoder.encode(clientSecret, "UTF-8") +
                        "&scope=" + URLEncoder.encode(scope, "UTF-8");

        // 剩余代码保持不变...
        // 发送POST请求
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
        connection.setDoOutput(true);

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = params.getBytes("UTF-8");
            os.write(input, 0, input.length);
        }

        // 读取响应
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }

                ObjectMapper mapper = new ObjectMapper();
                return mapper.readValue(response.toString(), com.lxs.gitee001.model.response.TokenResponse.class);
            }
        } else {
            // 错误处理
            throw new IOException("获取token失败，HTTP状态码: " + responseCode);
        }
    }

    /**
     * 使用refresh_token刷新access_token
     */
    public response.TokenResponse refreshAccessToken(String refreshToken) throws IOException {
        String url = "https://gitee.com/oauth/token";

        String params = "grant_type=refresh_token" +
                "&refresh_token=" + URLEncoder.encode(refreshToken, "UTF-8") +
                "&client_id=" + URLEncoder.encode(clientId, "UTF-8") +
                "&client_secret=" + URLEncoder.encode(clientSecret, "UTF-8");

        // 发送POST请求（代码同上）
        // ...
        return null; // 实际实现参考上面的getAccessToken方法
    }


    /**
     * 密码模式获取access_token
     */
    public response.TokenResponse getAccessTokenByPassword(String username, String password, String scope) throws IOException {
        String url = "https://gitee.com/oauth/token";

        // 构建请求参数
        String params = "grant_type=password" +
                "&username=" + URLEncoder.encode(username, "UTF-8") +
                "&password=" + URLEncoder.encode(password, "UTF-8") +
                "&client_id=" + URLEncoder.encode(clientId, "UTF-8") +
                "&client_secret=" + URLEncoder.encode(clientSecret, "UTF-8") +
                "&scope=" + URLEncoder.encode(scope, "UTF-8");

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"); // 重要：避免403错误
        connection.setDoOutput(true);

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = params.getBytes("UTF-8");
            os.write(input, 0, input.length);
        }

        // 读取响应
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }

                ObjectMapper mapper = new ObjectMapper();
                return mapper.readValue(response.toString(), com.lxs.gitee001.model.response.TokenResponse.class);
            }
        } else {
            // 错误处理
            throw new IOException("获取token失败，HTTP状态码: " + responseCode);
        }
    }
}
